package com.northpool.operator.dataset.operation;

import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.annotation.OperatorInfo;
import com.northpool.operator.common.algorithm.OperatorTestBuild;
import com.northpool.operator.common.algorithm.TestParamBuilder;
import com.northpool.operator.common.database.DatabaseUtils;
import com.northpool.operator.param.ParamTool;
import com.northpool.operator.utils.StpOperatorHelper;
import com.northpool.resources.datasource.IDataSource;
import com.northpool.resources.datatable.operate.ITableOperator;

@OperatorInfo(
        ref = "TableReNameOperator",
        version = "0.0.1",
        name = "表名变更",
        description = "数据表表名变更为新表名"
)
public class TableReNameOperator extends StpOperatorHelper {

    @InputParams({
            @InputParam(ref = "datasource", name = "数据源", desc = "数据源ID"),
            @InputParam(ref = "tableName", name = "表名称", desc = "数据表名称，如: public.tb_test"),
            @InputParam(ref = "newTableName", name = "新表名称", desc = "数据表名称，如: tb_test_new"),
    })
    public TableReNameOperator() {
    }

    public static void main(String[] args) throws Exception {
        OperatorTestBuild.execute(TableReNameOperator.class,
                TestParamBuilder.aBuilder()
                        .param("datasource", "test_bcg")
                        .param("tableName", "dltb_building_b_all_new")
                        .param("newTableName", "dltb_building_b_all")
                        .build());
    }

    @Override
    public void execute(ParamTool paramTool) throws Exception {
        String datasource = paramTool.getStr("datasource");
        String dataSourceJson = DatabaseUtils.getDataSourceJson(datasource);
        String tableName = paramTool.getStr("tableName");
        String newTableName = paramTool.getStr("newTableName");
        IDataSource ds = IDataSource.fromJSON(dataSourceJson);
        ITableOperator tableOperator = ds.getTableOperator(tableName);
        tableOperator.renameTableName(newTableName);
        this.log("表名变更为: {}", newTableName);
    }
}
